<?php
/*
 * SoloPHP PHP框架
 * $Author: Yotianya <yotianya@gmail.com>
 * $Dtime:2011-10-24
 * $Copyright: CopyRight By SoloPHP Yotianya
 */
 

class Mysql{
	
	/* db_mysql MySQL数据库的驱动支持 */
	public $conn;	//数据库链接句柄
	public $arrSql; //执行的SQL语句记录


	/**
	 * 构造函数
	 *
 	 * @param dbConfig  数据库配置
 	 */
	public function __construct($dbConfig)
	{
		$linkfunction = ( TRUE == $GLOBALS['C']['DB']['Persistent'] ) ? 'mysql_pconnect' : 'mysql_connect';
		$this->conn = $linkfunction($GLOBALS['C']['DB']['DBhost'].":".$GLOBALS['C']['DB']['DBport'], $GLOBALS['C']['DB']['DBuser'], $GLOBALS['C']['DB']['DBpsw']) or errorMsg('dbConnectFail',mysql_error());
		mysql_select_db($GLOBALS['C']['DB']['DBname'], $this->conn) or errorMsg('DBNameError',$GLOBALS['C']['DB']['DBname']);
		$this->exec('SET NAMES '.$GLOBALS['C']['DB']['DBcharSet']);
	}

	/**
 	 * 按SQL语句获取记录结果，返回数组
 	 *
 	 * @param sql  执行的SQL语句
 	 */
	public function getArray($sql)
	{
		if( ! $result = $this->exec($sql) )return FALSE;
		if( ! mysql_num_rows($result) )return FALSE;
		$rows = array();
		while($rows[] = mysql_fetch_array($result,MYSQL_ASSOC)){}
		mysql_free_result($result);
		array_pop($rows);
		return $rows;
	}

	/**
 	 * 返回当前插入记录的主键ID
 	 */
	public function newinsertid()
	{
		return mysql_insert_id($this->conn);
	}

	/**
 	 * 格式化带limit的SQL语句
 	 */
	public function setlimit($sql, $limit)
	{
		return $sql. " LIMIT {$limit}";
	}

	/**
 	 * 执行一个SQL语句
 	 *
 	 * @param sql 需要执行的SQL语句
 	 */
	public function exec($sql)
	{
		$this->arrSql[] = $sql;
		if( $result = mysql_query($sql, $this->conn)){
			return $result;
		}else{
            errorMsg('error','执行错误'. mysql_error());
		}
	}

	/**
 	 * 返回影响行数
	 */
	public function affected_rows()
	{
		return mysql_affected_rows($this->conn);
	}

	/**
 	 * 获取数据表结构
 	 *
	 * @param tbl_name  表名称
 	 */
	public function getTable($tbl_name)
	{
		return $this->getArray("DESCRIBE $tbl_name");
	}


	/**
 	 * 对特殊字符进行过滤
	 *
 	 * @param value  值
 	 */
	public function escape($value) {

		if(is_null($value))return 'NULL';
		if(is_bool($value))return $value ? 1 : 0;
		if(is_int($value))return (int)$value;
		if(is_float($value))return (float)$value;
		if(@get_magic_quotes_gpc())$value = stripslashes($value);
		return '\''.mysql_real_escape_string($value, $this->conn).'\'';
	}

	/**
  	 * 析构函数
 	 */
	public function __destruct()
	{
		if( TRUE != $GLOBALS['C']['DB']['Persistent'] )@mysql_close($this->conn);
	}
}